<template>
  <view class="container">
    <!-- 周次选择器 -->
    <view class="week-selector">
      <view class="selector-header">
        <text class="header-title">课程安排</text>
        <text class="header-subtitle">选择周次查看课程安排</text>
      </view>

      <view class="week-tabs">
        <view 
          class="week-tab" 
          :class="{ active: currentWeekIndex === index }" 
          v-for="(week, index) in weekList"
          :key="index" 
          @click="selectWeek(index)"
        >
          <!-- 使用formatWeekDisplay格式化周次显示 -->
          <text class="week-text">{{ formatWeekDisplay(week.week) }}</text> 
        </view>
      </view>
    </view>

    <!-- 课程安排图片 -->
    <view class="course-content">
      <view class="course-image-container" v-if="getImageUrl(currentWeek.imageUrl)">
        <image 
          class="course-image" 
          :src="getImageUrl(currentWeek.imageUrl)" 
          mode="widthFix" 
          @click="previewImage"
          @error="onImageError"
        ></image>
        <view class="image-tip">
          <text class="tip-text">点击图片可放大查看</text>
        </view>
      </view>

      <!-- 空状态 -->
      <view class="empty-state" v-else>
        <view class="empty-icon">
          <text class="icon-text">📅</text>
        </view>
        <text class="empty-title">暂无课程安排</text>
        <text class="empty-desc">该周次暂无课程安排，请稍后再查看</text>
      </view>
    </view>

    <!-- 课程信息 -->
    <view class="course-info" v-if="getImageUrl(currentWeek.imageUrl)">
      <view class="info-header">
        <text class="info-title">课程信息</text>
      </view>
      <view class="info-content">
        <view class="info-item">
          <text class="info-label">周次：</text>
          <!-- 使用formatWeekDisplay格式化周次显示 -->
          <text class="info-value">{{ formatWeekDisplay(currentWeek.week) }}</text> 
        </view>
        <view class="info-item">
          <text class="info-label">更新时间：</text>
          <!-- 使用formatDateTime格式化时间显示 -->
          <text class="info-value">{{ formatDateTime(currentWeek.uploadTime) }}</text> 
        </view>
      </view>
    </view>
  </view>
</template>

<script>
	import {
		API_CONFIG,
		getApiUrl,
		apiRequest
	} from '@/config/api.js'
	export default {
		data() {
			return {
				currentWeekIndex: 0,
				weekList: []
			}
		},
		computed: {
			currentWeek() {
				return this.weekList[this.currentWeekIndex] || {};
			}
		},
		onLoad() {
			this.loadWeekData()
		},
		methods: {
			async loadWeekData() {
				try {
					const url = getApiUrl(API_CONFIG.ENDPOINTS.COURSE_SCHEDULE_ALL);
					console.log('请求课程数据URL:', url);
					const res = await apiRequest({
						url,
						method: 'GET'
					});
					console.log('课程数据响应:', res);
					// 假设后端返回 { code: 200, data: [...] } 格式，根据实际调整
					if (res.code === 200) {
						// 处理图片URL，过滤掉临时路径
						this.weekList = res.data.map(week => {
							let imageUrl = week.imageUrl
							
							// 如果是对象类型，直接设置为空字符串
							if (typeof imageUrl === 'object' && imageUrl !== null) {
								console.warn('图片URL是对象类型，设置为空字符串:', imageUrl)
								imageUrl = ''
							}
							
							// 如果是字符串类型，检查是否是临时路径
							if (typeof imageUrl === 'string' && imageUrl) {
								if (imageUrl.includes('tmp/') || imageUrl.includes('http://tmp/') || imageUrl.includes('__tmp__/')) {
									console.warn('检测到临时路径图片URL，设置为空字符串:', imageUrl)
									imageUrl = ''
								}
							}
							
							return {
								...week,
								imageUrl: imageUrl
							}
						});
						console.log('设置周次数据:', this.weekList);
					} else {
						uni.showToast({
							title: res.message || '获取周次数据失败',
							icon: 'none'
						});
					}
				} catch (error) {
					uni.showToast({
						title: '请求出错，请稍后重试',
						icon: 'none'
					});
					console.error('请求课程周次数据失败：', error);
				}
			},
			selectWeek(index) {
				this.currentWeekIndex = index
			},
			// 格式化周次显示
			formatWeekDisplay(weekDate) {
				if (!weekDate) return '未知周次'
				const date = new Date(weekDate)
				const year = date.getFullYear()
				const weekNumber = this.getWeekOfYear(date)
				return `${year}年第${weekNumber}周`
			},
			// 获取年份中的第几周
			getWeekOfYear(date) {
				const d = new Date(Date.UTC(date.getFullYear(), date.getMonth(), date.getDate()))
				const dayNum = d.getUTCDay() || 7
				d.setUTCDate(d.getUTCDate() + 4 - dayNum)
				const yearStart = new Date(Date.UTC(d.getUTCFullYear(), 0, 1))
				return Math.ceil((((d - yearStart) / 86400000) + 1) / 7)
			},
			// 格式化日期时间显示
			formatDateTime(dateTime) {
				if (!dateTime) return '未知时间'
				const date = new Date(dateTime)
				return `${date.getFullYear()}-${String(date.getMonth()+1).padStart(2,'0')}-${String(date.getDate()).padStart(2,'0')} ${String(date.getHours()).padStart(2,'0')}:${String(date.getMinutes()).padStart(2,'0')}`
			},
			previewImage() {
				const imageUrl = this.getImageUrl(this.currentWeek.imageUrl)
				if (!imageUrl) {
					uni.showToast({
						title: '暂无图片',
						icon: 'none'
					})
					return
				}
				
				uni.previewImage({
					urls: [imageUrl],
					current: imageUrl
				});
			},

			// 获取图片URL，处理临时路径和localhost
			getImageUrl(url) {
				// 如果URL为空或不是字符串，返回空字符串
				if (!url || typeof url !== 'string') {
					return ''
				}
				
				// 检查是否是临时路径
				if (url.includes('tmp/') || url.includes('http://tmp/') || url.includes('__tmp__/')) {
					console.warn('检测到临时路径图片URL:', url)
					return ''
				}
				
				// 如果已经是完整URL，检查是否需要替换localhost（处理8080和8090端口）
				if (url.startsWith('http://') || url.startsWith('https://')) {
					if (url.includes('localhost:8080') || url.includes('localhost:8090')) {
						return url.replace(/http:\/\/localhost:(8080|8090)/, API_CONFIG.BASE_URL)
					}
					return url
				}
				
				// 如果是相对路径（以/开头），转换为完整的服务器URL
				if (url.startsWith('/')) {
					return `${API_CONFIG.BASE_URL}${url}`
				}
				
				// 其他情况，尝试添加基础URL
				return `${API_CONFIG.BASE_URL}/${url}`
			},

			// 图片加载错误处理
			onImageError() {
				console.error('图片加载失败')
			}
		}
	}
</script>

<style lang="scss" scoped>
	.container {
		min-height: 100vh;
		background: linear-gradient(135deg, #0B0F1A 0%, #1a1f2e 100%);
		padding: 0;
	}

	.week-selector {
		background: #1a1f2e;
		padding: 30rpx 20rpx;
		border-bottom: 1rpx solid #2a2f3e;

		.selector-header {
			margin-bottom: 30rpx;

			.header-title {
				display: block;
				font-size: 36rpx;
				color: #FFFFFF;
				font-weight: bold;
				margin-bottom: 8rpx;
			}

			.header-subtitle {
				font-size: 26rpx;
				color: #AAB4BE;
			}
		}

		.week-tabs {
			display: flex;
			overflow-x: auto;
			gap: 20rpx;

			.week-tab {
				flex-shrink: 0;
				padding: 20rpx 30rpx;
				background: #2a2f3e;
				border-radius: 12rpx;
				border: 1rpx solid #3a3f4e;
				transition: all 0.3s ease;

				&.active {
					background: linear-gradient(135deg, #1976D2 0%, #2196F3 100%);
					border-color: #1976D2;
				}

				.week-text {
					font-size: 28rpx;
					color: #FFFFFF;
					white-space: nowrap;
				}
			}
		}
	}

	.course-content {
		padding: 30rpx 20rpx;

		.course-image-container {
			background: #1a1f2e;
			border-radius: 16rpx;
			padding: 20rpx;
			border: 1rpx solid #2a2f3e;

			.course-image {
				width: 100%;
				border-radius: 12rpx;
				box-shadow: 0 4rpx 16rpx rgba(0, 0, 0, 0.3);
			}

			.image-tip {
				text-align: center;
				margin-top: 20rpx;

				.tip-text {
					font-size: 24rpx;
					color: #AAB4BE;
				}
			}
		}

		.empty-state {
			background: #1a1f2e;
			border-radius: 16rpx;
			padding: 80rpx 40rpx;
			text-align: center;
			border: 1rpx solid #2a2f3e;

			.empty-icon {
				width: 120rpx;
				height: 120rpx;
				border-radius: 50%;
				background: linear-gradient(135deg, rgba(25, 118, 210, 0.1) 0%, rgba(0, 184, 212, 0.1) 100%);
				display: flex;
				align-items: center;
				justify-content: center;
				margin: 0 auto 30rpx;

				.icon-text {
					font-size: 60rpx;
				}
			}

			.empty-title {
				display: block;
				font-size: 32rpx;
				color: #FFFFFF;
				font-weight: bold;
				margin-bottom: 16rpx;
			}

			.empty-desc {
				font-size: 26rpx;
				color: #AAB4BE;
			}
		}
	}

	.course-info {
		margin: 30rpx 20rpx;
		background: #1a1f2e;
		border-radius: 16rpx;
		padding: 30rpx;
		border: 1rpx solid #2a2f3e;

		.info-header {
			margin-bottom: 20rpx;

			.info-title {
				font-size: 32rpx;
				color: #FFFFFF;
				font-weight: bold;
			}
		}

		.info-content {
			.info-item {
				display: flex;
				margin-bottom: 16rpx;

				&:last-child {
					margin-bottom: 0;
				}

				.info-label {
					font-size: 28rpx;
					color: #AAB4BE;
					width: 160rpx;
				}

				.info-value {
					font-size: 28rpx;
					color: #FFFFFF;
					flex: 1;
				}
			}
		}
	}
</style>